package com.effect.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import static java.util.Collections.singletonList;

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    // @Bean
    // public Docket createRestApi(){
    //     // 添加全局参数  把所有的请求都增加一个请求头入参
    //    // return new Docket(DocumentationType.OAS_30)
    //     return new Docket(DocumentationType.SWAGGER_2)
    //             .apiInfo(apiInfo())
    //             .enable(true)
    //             .select()
    //             .apis(RequestHandlerSelectors.basePackage("com.effect"))
    //             .paths(PathSelectors.any()).build()
    //             .globalRequestParameters(
    //                     singletonList(new springfox.documentation.builders.RequestParameterBuilder()
    //                             // 不能叫Authorization
    //                             .name("x-auth-token")
    //                             .description("x-auth-token")
    //                             .in(ParameterType.HEADER)
    //                             .required(false)
    //                             .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
    //                             .build()))
    //             ;
    // }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.effect"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(singletonList(apiKey()))
                .securityContexts(singletonList(securityContext()));
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(singletonList(defaultAuth()))
                .forPaths(PathSelectors.any())
                .build();
    }

    // 配置ui页面上显示的信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("effect-Service")
                .description("effect-api文档")
                .version("1.0.0")
                .build();
    }


    private SecurityScheme apiKey() {
        return new ApiKey("apiKey", "x-auth-token", "header");
    }

    private SecurityReference defaultAuth() {
        return new SecurityReference("apiKey", new AuthorizationScope[0]);
    }
}
